<template>
  <div class="search-container">
    <SearchInput showBack v-model="word" @onSearch="onSearch" />
    <van-loading v-show="loading" vertical color="#0094ff">
      加载中...
    </van-loading>
    <van-list
      v-model="listLoading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
      v-if="word && list.length"
    >
      <GoodsList :list="list" />
    </van-list>
    <GoodsEmpty
      v-else-if="word && list.length === 0 && isSearch"
      img="search"
      title="未找到商品"
    />
  </div>
</template>
<script>
export default {
  async asyncData({ query, app }) {
    const word = query.word;
    let finished = false,
      isSearch = false;
    if (!word) return { finished, isSearch };
    try {
      const res = await app.$apiGetGoodsList({ word, pagesize: 5 });
      const { data, pagesize, page, total } = res;
      finished = page * pagesize > total;
      isSearch = true;
      return { list: data, finished, word, page: page + 1, isSearch };
    } catch (error) {
      console.log(error);
      return {};
    }
  },
  data() {
    return {
      word: "",
      list: [],
      loading: false,
      listLoading: false,
      finished: false,
      isSearch: false,
      page: 1,
      pagesize: 10
    };
  },
  methods: {
    onSearch(val) {
      this.$router.push({
        name: "search",
        query: {
          word: val
        }
      });
    },
    onLoad() {
      if (this.page === 1) {
        return (this.listLoading = false);
      }
      const { word, page } = this;
      this.getList({ word, page });
    },
    getList(data) {
      data.pagesize = 5;
      this.loading = true;
      this.$apiGetGoodsList(data)
        .then(res => {
          const { data, status, pagesize, page, total } = res;
          if (status === 0) {
            this.list = this.list.concat(data);
            this.page = page + 1;
            this.finished = page * pagesize > total;
          }
        })
        .finally(() => {
          this.isSearch = true;
          this.loading = false;
        });
    }
  },
  watchQuery: ["word"]
};
</script>
<style lang="scss" scoped>
.search-container {
  position: relative;
  padding: 50px 0 50px;
  height: 100vh;
  box-sizing: border-box;
  overflow-y: auto;
  .van-loading {
    position: absolute;
    top: 50px;
    left: 0;
    right: 0;
    height: calc(100vh - 50px);
    background: #fff;
    justify-content: center;
  }
  .search-input {
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    background: none;
    ::v-deep input {
      border-color: #e9e9e9;
    }
  }
}
</style>
